-- UIBuyFood
-- Create by huanghr
-- 购买食物界面

-- UIBuyFood继承自Layer
UIBuyFood = class("UIBuyFood", function()
    return cc.Layer:create();
end);

function UIBuyFood.create(classId)
    return UIBuyFood.new(classId);
end

-- 构造函数
function UIBuyFood:ctor(classId)
    self:setName("UIBuyFood");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/item/BuyFood.csb");
    self:addChild(node);
    self.node = node;

    -- 记录商品信息
    self.classId = classId;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UIBuyFood:registerEventCallback()
    -- 购买食材
    EventMgr.register("UIBuyFood", event.BUY_FOOD_MATERIAL, function(args)
        self:redraw();

        local lightNode2 = findChildByName(self.node, "CT/item/bg");
        lightNode2:removeAllChildren();

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode2, 1231, 93, 9,  nil, 0.82);
        else
            playEffect(lightNode2, 1180, 93, 9,  nil, 0.82);
        end
    end);

    -- 购买装置材料
    EventMgr.register("UIBuyFood", event.BUY_DEVICE_MATERIAL, function(args)
        self:redraw();

        local lightNode2 = findChildByName(self.node, "CT/item/bg");
        lightNode2:removeAllChildren();

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode2, 1231, 93, 9,  nil, 0.82);
        else
            playEffect(lightNode2, 1180, 93, 9,  nil, 0.82);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIBuyFood 界面析构清理");
            EventMgr.removeAll("UIBuyFood");

            local uiForm = UIMgr:getCurrentScene():getFormByName("UIGainItemPath");
            if uiForm ~= nil then
                uiForm:redraw();
            end
        end
    end);
end

-- 注册点击事件
function UIBuyFood:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIBuyFood");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 购买个数
    local str = getLocStr("bulk_purchase");
    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price1_btn");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(10);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 10));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price2_btn");
    local function onBuyClick2(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(1);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick2);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 1));
end

-- 重绘
function UIBuyFood:redraw()
    -- 需要替换角标图案为升级的
    local subBgLeft = findChildByName(self.node, "CT/bg_type");
    local subBgRight = findChildByName(self.node, "CT/bg_type2");

    -- 根据要合成的物品类型，选择界面的类型
    local itemGroup = ItemM.query(self.classId, "group");
    if itemGroup == 19 or itemGroup == 20 then
        -- 是食物或者食材
        subBgLeft:loadTexture(getTitleBgIconPath("food"));
        subBgRight:loadTexture(getTitleBgIconPath("food"));
    else
        subBgLeft:loadTexture(getTitleBgIconPath("upgrade"));
        subBgRight:loadTexture(getTitleBgIconPath("upgrade"));
    end

    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("title");

    local foodName = ItemM.query(self.classId, "name");
    nameLabel:setString(foodName);
    TextStyleM.setTitleStyle(nameLabel);

    local subHeadLabel = findChildByName(self.node, "CT/subhead");

    -- 先停止滚动
    if self.scrollingData and self.scrollingData.classId ~= self.classId then
        stopScrolling(subHeadLabel);
    end

    -- 当前拥有的数量
    local itemAmount = ItemM.getAmount(ME.user, self.classId);
    TextStyleM.setSubheadStyle(subHeadLabel);
    local curAmount = ItemM.getAmount(ME.user, self.classId);
    local scrollingData = self.scrollingData;

    -- 没有滚动过
    if not scrollingData or scrollingData.classId ~= self.classId then
        subHeadLabel:setString(string.format(getLocStr("own_num"), ItemM.getAmount(ME.user, self.classId)));

        self.scrollingData = {
            ["lastAmount"] = curAmount,
            ["classId"]    = self.classId,
        };
    else
        -- 滚动
        numScrolling(subHeadLabel, getLocStr("own_num"), scrollingData.lastAmount, curAmount, 30);

        scrollingData.lastAmount = curAmount;
    end

    -- 获取价格节点
    local priceNode1 = findChildByName(self.node, "CT/price1");
    local priceNode2 = findChildByName(self.node, "CT/price2");

    -- 根据物品类型，使用不同的价格底图
    local price = ItemM.query(self.classId, "buy_price");
    local priceBg1 = findChildByName(priceNode1, "price_bg");
    local priceBg2 = findChildByName(priceNode2, "price_bg");
    if price[1][1] == 1 then
        -- 是物品
        priceBg1:loadTexture(getCompoundItemIconPath("fragment_bg"));
        priceBg2:loadTexture(getCompoundItemIconPath("fragment_bg"));
    elseif price[1][1] == 2 then
        -- 是属性
        priceBg1:loadTexture(getCompoundItemIconPath("price"));
        priceBg2:loadTexture(getCompoundItemIconPath("price"));
    end

    local priceLabel1 = findChildByName(priceNode1, "price_label");
    local priceLabel2 = findChildByName(priceNode2, "price_label");

    local materialPrice = price[1][3];
    priceLabel1:setString(materialPrice*10);
    priceLabel2:setString(materialPrice);

    local btnBuy1 = findChildByName(self.node, "CT/price1_btn");
    local btnBuy2 = findChildByName(self.node, "CT/price2_btn");

    -- 获取金钱
    -- 获取当前用户的金币数量
    local moneyCount;
    if price[1][1] == 1 then
        -- 是物品
        moneyCount = ItemM.getAmount(ME.user, price[1][2]);
    elseif price[1][1] == 2 then
        -- 是属性
        moneyCount = ME.user:queryAttrib(price[1][2]);
    end

    if moneyCount >= materialPrice*10 then
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy1:setBright(true);
        btnBuy1:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy1:setBright(false);
        btnBuy1:setTouchEnabled(false);
    end
    if moneyCount >= materialPrice then
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy2:setBright(true);
        btnBuy2:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy2:setBright(false);
        btnBuy2:setTouchEnabled(false);
    end

    local item = findChildByName(self.node, "CT/item");

    -- 物品图标
    local iconImg = findChildByName(item, "icon");
    iconImg:loadTexture(getItemIconPath(ItemM.query(self.classId, "icon")));

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    local rank = ItemM.query(self.classId, "rank");
    local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end

    -- 物品的背景框
    local frameImage = findChildByName(item, "bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));
end

-- 适配
function UIBuyFood:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIBuyFood:tryBuy(amount)
    -- 判断能否购买
    local ret = self:canBuyFoodMaterial(self.classId, amount);
    if true ~= ret then
        if "money_lack" == ret then
            -- 金币不足
            alert(getLocStr("not_enough_money"));
            return;
        elseif "item_lack" == ret then
            -- 道具不足
            alert(string.format(getLocStr("not_enough_item"), ItemM.query(self.classId, "name")));
            return;
        else
            trace("UIBuyFood", "无法购买食材，原因：%s", tostring(ret));
            return;
        end
    end

    -- 关闭当前界面
    -- 执行购买
    local price = ItemM.query(self.classId, "buy_price");
    if price[1][1] == 1 then
        -- 物品
        Operation.cmd_buy_device_material(self.classId, amount);
    elseif price[1][1] == 2 then
        -- 属性
        Operation.cmd_buy_food_material(self.classId, amount);
    end
end

-------------------------------
-- 判断能否购买食材
-- @param classId   食材id
-- @param count     购买数量
function UIBuyFood:canBuyFoodMaterial(classId, count)
    local buyPrice = ItemM.query(classId, "buy_price");
    if not buyPrice then
        trace("PetM", "尚未配置食材(%d)的购买价格，无法购买。", classId);
        return false;
    end

    local price = buyPrice[1];
    if price[1] == 1 then
        -- 如果是道具
        if ItemM.getAmount(ME.user, price[2]) < count * price[3] then
            return "item_lack";
        end
    elseif price[1] == 2 then
        -- 如果是属性
        if ME.user:queryAttrib(price[2]) < count * price[3] then
            -- 金钱不足
            return price[2] .. "_lack";
        end
    end

    return true;
end
